﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace CopyIt
{
    public class Wildcard : Regex
    {
        /// <summary>
        /// Initializes a wildcard with the given search pattern.
        /// </summary>
        /// <param name="pattern">The wildcard pattern to match.</param>
        public Wildcard(string pattern)
            : base(WildcardToRegex(pattern))
        {
        }

        /// <summary>
        /// Initializes a wildcard with the given search pattern and options.
        /// </summary>
        /// <param name="pattern">The wildcard pattern to match.</param>
        /// <param name="options">A combination of one or more
        /// <see cref="System.Text.RegexOptions"/>.</param>
        public Wildcard(string pattern, RegexOptions options)
            : base(WildcardToRegex(pattern), options)
        {
        }

        /// <summary>
        /// Converts a wildcard to a regex.
        /// </summary>
        /// <param name="pattern">The wildcard pattern to convert.</param>
        /// <returns>A regex equivalent of the given wildcard.</returns>
        private static string WildcardToRegex(string wildcard)
        {
            StringBuilder sb = new StringBuilder(wildcard.Length + 8);
            sb.Append("^");
            for (int i = 0; i < wildcard.Length; i++)
            {
                char c = wildcard[i];
                switch (c)
                {
                    case '*':
                        sb.Append(".*");
                        break;
                    case '?':
                        sb.Append(".");
                        break;
                    case '\\':
                        if (i < wildcard.Length - 1)
                            sb.Append(Regex.Escape(wildcard[++i].ToString()));
                        break;
                    default:
                        sb.Append(Regex.Escape(wildcard[i].ToString()));
                        break;
                }
            }
            sb.Append("$"); 
            return sb.ToString();
        }
    }
}

//string[] files = System.IO.Directory.GetFiles(
// System.Environment.GetFolderPath(
// Environment.SpecialFolder.Personal));

//// Create a new wildcard to search for all
//// .txt files, regardless of case
//Wildcard wildcard = new Wildcard("*.txt", RegexOptions.IgnoreCase);

//// Print all matching files
//foreach(string file in files)
// if(wildcard.IsMatch(file))
//  Console.WriteLine(file);